package model.service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import model.ThreadHandler;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.os.Message;
import android.util.Log;

import com.VanDoren.ArgusV2.R;

@SuppressWarnings("unused")
public class ServiceConnection extends AsyncTask<String, String, String>
{
	private static final String TAG = ServiceConnection.class.getSimpleName();

	private static String BASE_URL = "http://192.168.30.231:1111/get/";
	
	private boolean updateCall;
	
	private ThreadHandler _handler;
	private String _id;
	

	public ServiceConnection(boolean varsOrNot, ThreadHandler handler)
	{
		updateCall = varsOrNot;
		_handler = handler;
	}
	
	@Override
	protected String doInBackground(String... uri) 
	{
		_id = uri[0];
		String url = BASE_URL + _id;
			
		try 
		{
			return baseRequest(url);
		} 
		catch (Exception e) 
		{
			sendMessage(R.id.connectionFailed, _id); // connectionfailed sends along the ID so the right holder can alert the view to this.
			e.printStackTrace();
		}
		return null;
	}
	
	private String baseRequest(String url) throws Exception
	{
		// create and make the call
		HttpClient httpClient = new DefaultHttpClient();
        String responseString = null;
    	HttpGet getter = new HttpGet(url);
    	HttpResponse response = httpClient.execute(getter);
    	
    	// catch the response
        StatusLine statusLine = response.getStatusLine();        
        boolean connectionStatusIsEqualToOK = statusLine.getStatusCode() == HttpStatus.SC_OK;
        
        if(connectionStatusIsEqualToOK)
        {
        	//translate response to a String
        	ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            responseString = out.toString();            
            out.close();
            
            return responseString;
        } 
        else
        {
            //Close connection
            response.getEntity().getContent().close();
            sendMessage(R.id.connectionFailed, _id); // connectionfailed sends along the ID so the right holder can alert the view to this.
            throw new IOException(statusLine.getReasonPhrase());
        }
	}

	@Override
	protected void onPostExecute(String result) 
	{
		if(result == null)
			sendMessage(R.id.connectionFailed, _id);
		else if(result.trim().isEmpty())
			sendMessage(R.id.nonExistantMachine, _id);
		else
		{
			// create the correct translator
			ServiceBehaviour translator;
			if(result.startsWith("<")) // XML always starts with this token and JSON starts with spaces or [
			{
				// XML (temporarily says new JsonBehaviour because the translator has to be initialized in all paths
				translator = new JsonBehaviour();				
			}
			else
			{
				//JSON
				translator = new JsonBehaviour();
			}
			
			// translate the result and send it to the handler
			try 
			{
				if(updateCall)
				{				
					sendMessage( R.id.updatedVarsForMachineReceived, translator.translateResponseToMachine(result));
				}
				else
				{				
					sendMessage( R.id.newMachineReceived, translator.translateResponseToMachine(result));				
				}			
			}
			catch(Exception e)
			{
				// translationFailed sends along along the ID so the right holder can alert the view to this.
				sendMessage(R.id.translationFailed, _id);
			}
		}
	}
	
	//sends a message to the handler
	private void sendMessage(int msgId, Object data)
	{
		Message message = Message.obtain(_handler, msgId);
		message.obj = data;
		message.sendToTarget();
	}
} // end of class
